# frozen_string_literal: true

class SchemaService < ApplicationService
  class << self
    def create(params)
      schema = Schema.transaction do
        schema = Schema.create params.slice(:name, :description)
        schema.input_variables.create! build_variable_params(params[:input_variables])
        schema.output_variables.create! build_variable_params(params[:output_variables])
        schema
      end
      { code: 0, message: 'success', schema: schema.as_json(schema_to_json_fmt) }
    rescue StandardError => e
      logger.error e
      { code: 1, message: e.message }
    end

    def update(id, params)
      schema = Schema.find(id)
      Schema.transaction do
        schema.update!(params.slice(:name, :description))
        # TOTO, update input_variables & output_variables
      end
      { code: 0, message: 'success', schema: schema.as_json(schema_to_json_fmt) }
    end

    def delete(id)
      Schema.destroy(id)
      { code: 0, message: 'success' }
    end

    def search(params)
      schemas = Schema.filter_name(params[:name])
        .filter_status(params[:status])
      total = schemas.count
      schemas = schemas.page_info(params[:page_size], params[:page_no])
        .includes(:input_variables, :output_variables)
        .as_json(schema_to_json_fmt)
      { code: 0, message: 'success', total: total, schemas: schemas.as_json(schema_to_json_fmt) }
    end

    def show(id)
      schema = Schema.find id
      { code: 0, message: 'success', schema: schema.as_json(schema_to_json_fmt) }
    rescue StandardError => e
      logger.error e
      { code: 1, message: e.message }
    end

    private

    def schema_to_json_fmt
      {
        include: %i[input_variables output_variables]
      }
    end

    def build_variable_params(variables_params)
      variables_params.each_with_index.map do |variable, index|
        variable.slice(:variable_type_id, :name, :nullable, :default_value).merge(ordinal: index)
      end
    end
  end
end
